let activeIndex = 1,
  limit = 0,
  disabled = false,
  $stage,
  $controls,
  cavas = false;

const SPIN_FORWARD_CLASS = "js-spin-fWd",
  SPIN_BACKWARD_CLASS = "js-spin-bWd",
  DISABLE_TRANSITION_CLASS = "js-disable-transition",
  SPIN_DUR = 1000;

/**
 *
 * @param {string} s
 * @param {Document} d
 * @returns {HTMLElement}
 */
const $ = (s, d = document) => d.querySelector(s);
const $$ = (s, d = document) => d.querySelectorAll(s);
const carouselControl = $(".carousel_control");

/**
 *
 * @param {HTMLElement} el
 * @returns
 */
const last = (eles) => {
  if (!eles.length) return null;
  return eles.children[eles.children.length - 1];
};

/**
 *
 * @param {HTMLCollection} eles
 * @param {string} className
 */
const removeEleClass = (eles, className) => {
  if (!eles.length) return;
  eles.forEach((e) => e.classList.remove(className));
};

const appendControls = () => {
  const frag = document.createDocumentFragment();
  for (let i = 0; i < limit; i++) {
    const a = document.createElement("a");
    a.dataset.index = i;
    a.setAttribute("href", "#");
    frag.appendChild(a);
  }
  carouselControl.appendChild(frag);
  const aEles = $$(".carousel_control a");
  removeEleClass(aEles, "active");
  aEles[activeIndex].classList.add("active");
};

const setIndexes = () => {
  const spinners = $$(".spinner_face");
  spinners.forEach((s, i) => {
    s.dataset.index = i;
    limit++;
  });
};

const spin = (inc = 1) => {
  if (disabled) return;
  if (!inc) return;
  activeIndex += inc;
  disabled = true;
  if (activeIndex >= limit) activeIndex = 0;
  if (activeIndex < 0) activeIndex = limit - 1;
  const $activeEls = $(".spinner_face.js-active");
  const $nextEls = $(`.spinner_face[data-index=${activeIndex}]`);
  $nextEls.classList.add("js-next");

  if (inc > 0) {
    $stage.classList.add(SPIN_FORWARD_CLASS);
  } else {
    $stage.classList.add(SPIN_BACKWARD_CLASS);
  }
};

setIndexes();
appendControls();
console.log(limit);
